﻿using System;
using System.ComponentModel;
using System.Timers;
using System.Windows;
using System.Windows.Threading;
using SuppKids.Core;
using SuppKids.Core.Security;
using SuppKids.Licensing.Common;
using SuppKids.Resources;

namespace SuppKids.ViewModels
{
    public class LicenseService : ViewModelBase
    {
        private readonly LicensesManager licensesManager;
        private LicenseDTO licenseDTO;
        private readonly Timer timer = new Timer { AutoReset = true, Interval = 5 * 60 * 1000 }; // 5 minutes

        public LicenseService(LicensesManager licensesManager)
        {
            this.licensesManager = licensesManager;
            this.LicenseDTO = licensesManager.SelectActiveLicense();
            timer.Elapsed += CheckLicense;
            timer.Start();
        }

        public LicenseDTO LicenseDTO
        {
            get
            {
                return this.licenseDTO;
            }

            set
            {
                this.licenseDTO = value;
                this.OnPropertyChanged(Lambda.Property<LicenseService>(x => x.LicenseDTO));
                this.OnPropertyChanged(Lambda.Property<LicenseService>(x => x.IsSoftwareActive));
            }
        }

        public bool IsSoftwareActive
        {
            get
            {
                return this.LicenseDTO != null;
            }
        }

        public override bool AllFieldsIsNotEmpty
        {
            get { return true; }
        }

        public void Activate(string licenseString)
        {
            this.licensesManager.Activate(licenseString);
            this.LicenseDTO = licensesManager.SelectActiveLicense();
        }

        private void CheckLicense(object sender, ElapsedEventArgs elapsedEventArgs)
        {
            this.LicenseDTO = this.licensesManager.SelectActiveLicense();
            if (this.LicenseDTO == null)
            {
                if (MessageBox.Show(Messages.LicenseIsExpired, Labels.LicenseIsExpiredCaption,
                    MessageBoxButton.OK,
                    MessageBoxImage.Warning, MessageBoxResult.OK, MessageBoxOptions.ServiceNotification) ==
                    MessageBoxResult.OK)
                {
                    Environment.Exit(0);
                }
            }
        }

    }
}